package com.icez.seek_bar

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.SeekBar

/**
 * 拖动条
 * @sample 
 * @author Icez
 */
@SuppressLint("AppCompatCustomView")
class CustomSeekBar @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : SeekBar(context, attrs, defStyleAttr) {

    private var mTextPaint: Paint?= null

    private var mProgressTextRect: Rect?= null

    private var mBgBitmap:Bitmap ?= null

    // 拖动拇指的大小
    private var mThumbSize:Float = 0f

    // 父控件是否不限制绘制区域
    private var mParentClipChildren:Boolean = false

    // 提示文本大小
    private var mHintTextSize:Float = 0f

    // 提示文本颜色
    private var mHintTextColor:Int = Color.BLACK


    private var mCustomSeekBarAdapter:CustomSeekBarAdapter ?= null

    // 提示布局上面偏移量
    private var mHintViewTopOff:Float = 0f

    // 是否代理父控件触屏事件，为了增加拖动范围
    private var mIsProxyParentTouch:Boolean = false


    init {
        initStyleValue()

        mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mTextPaint?.textSize = mHintTextSize
        mTextPaint?.color = mHintTextColor

        mProgressTextRect = Rect()

        splitTrack = false


    }

    private fun initStyleValue(){
        val typedArray = context.obtainStyledAttributes(attrs,R.styleable.CustomSeekBar)
        mIsProxyParentTouch = typedArray.getBoolean(R.styleable.CustomSeekBar_isProxyParentTouch,false)
        mThumbSize = typedArray.getDimensionPixelOffset(R.styleable.CustomSeekBar_thumbSize,0).toFloat()
        mParentClipChildren = typedArray.getBoolean(R.styleable.CustomSeekBar_parentClipChildren,false)
        mHintTextSize = typedArray.getDimensionPixelOffset(R.styleable.CustomSeekBar_hintTextSize,20).toFloat()
        mHintTextColor = typedArray.getColor(R.styleable.CustomSeekBar_hintTextColor,Color.BLACK)
        mHintViewTopOff = typedArray.getDimensionPixelOffset(R.styleable.CustomSeekBar_hintViewTopOff,100).toFloat()
        typedArray.recycle()

    }


    /**
     * 设置适配器
     * @sample
     * @author Icez
     */
    fun setAdapter(mCustomSeekBarAdapter:CustomSeekBarAdapter){
        this.mCustomSeekBarAdapter = mCustomSeekBarAdapter
        val bgView = mCustomSeekBarAdapter?.getHintViewResId()
            ?.let { LayoutInflater.from(context).inflate(it,null,false) }
        mBgBitmap = viewToBitmap(bgView)
    }

    /**
     * 将一个未show的布局转换成bitmap
     */
    private fun viewToBitmap(view: View?): Bitmap {
        view?.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
        view?.layout(0, 0, view?.measuredWidth?:0, view?.measuredHeight?:0)
        val mH = view?.height?:0
        val mW = view?.width?:0
        val bitmap =
            Bitmap.createBitmap(mW, mH,Bitmap.Config.ARGB_8888)
        view?.draw(Canvas(bitmap))
        return bitmap
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        drawText(canvas)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        (parent as ViewGroup).clipChildren = mParentClipChildren
        if(mIsProxyParentTouch){
            (parent.parent as ViewGroup).clipChildren = mParentClipChildren
            (parent as ViewGroup).setOnTouchListener { view, motionEvent ->
                onTouchEvent(motionEvent)
            }
        }

    }

    /**
     * 绘制文本
     * @sample
     * @author Icez
     */
    private fun drawText(canvas: Canvas?){
        if(mCustomSeekBarAdapter==null){
            return
        }
        mTextPaint?.let {
            val str = mCustomSeekBarAdapter?.getHintText(progress)?:progress.toString()
            mTextPaint?.getTextBounds(str,0,str.length,mProgressTextRect)
            val progressRatio = progress/max.toFloat()
            var real:Float =mThumbSize - mThumbSize * progressRatio * 2
            val thumbX = width * progressRatio - (mProgressTextRect?.width()?:0)/2f + real
            val thumbY = - height + (mBgBitmap?.height?:0)/2f + (mProgressTextRect?.height()?:0)/2f - mHintViewTopOff -dpToPx (context,mCustomSeekBarAdapter?.getArrowHeight()?:0f)
            if(mBgBitmap!=null){
                val thumbX2 = width * progressRatio - (mBgBitmap?.width?:0)/2f + real
                val thumbY2 = - height - mHintViewTopOff
                mBgBitmap?.let { it1 -> canvas?.drawBitmap(it1,thumbX2,thumbY2,mTextPaint) }
            }

            canvas?.drawText(str,thumbX,thumbY,
                it
            )
        }
    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Log.e("icez","dddd")
        return super.onTouchEvent(event)
    }

    /**
     * dip 转 px
     * @sample
     * @author Icez
     * @param context 上下文
     * @param dpValue dp值
     */
    private fun dpToPx(context: Context, dpValue: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpValue,
            context.resources.displayMetrics
        ).toInt()
    }
}